/**
 * AI健康助手 - 主JavaScript文件
 * 提供完整的医疗问答系统功能
 */

class MedicalQAApp {
    constructor() {
        this.sessionId = this.generateSessionId();
        this.lastQuestion = null;
        this.lastAnswer = null;
        this.currentRating = 0;
        this.isRecording = false;
        this.recognition = null;
        this.dailyQueries = 0;
        this.responseTime = 0;
        
        this.initElements();
        this.attachEventListeners();
        this.initVoiceRecognition();
        this.loadSystemStatus();
        this.setupTheme();
    }

    initElements() {
        // 主要元素
        this.loadingOverlay = document.getElementById('loading-overlay');
        this.welcomeScreen = document.getElementById('welcome-screen');
        this.chatContainer = document.getElementById('chat-container');
        this.chatMessages = document.getElementById('chat-messages');
        this.questionInput = document.getElementById('question-input');
        this.sendBtn = document.getElementById('send-btn');
        
        // 控制元素
        this.themeToggle = document.getElementById('theme-toggle');
        this.clearChatBtn = document.getElementById('clear-chat');
        this.settingsBtn = document.getElementById('settings-btn');
        this.sidebarToggle = document.getElementById('sidebar-toggle');
        this.sidebar = document.getElementById('sidebar');
        
        // 功能按钮
        this.voiceInputBtn = document.getElementById('voice-input');
        this.imageUploadBtn = document.getElementById('image-upload');
        this.exportChatBtn = document.getElementById('export-chat');
        
        // 模态框
        this.modalOverlay = document.getElementById('modal-overlay');
        this.modalTitle = document.getElementById('modal-title');
        this.modalBody = document.getElementById('modal-body');
        this.modalClose = document.getElementById('modal-close');
        
        // 反馈面板
        this.feedbackPanel = document.getElementById('feedback-panel');
        this.starRating = document.getElementById('star-rating');
        this.feedbackText = document.getElementById('feedback-text');
        this.submitFeedbackBtn = document.getElementById('submit-feedback');
        this.skipFeedbackBtn = document.getElementById('skip-feedback');
        this.closeFeedbackBtn = document.getElementById('close-feedback');
        
        // 语音面板
        this.voicePanel = document.getElementById('voice-panel');
        this.stopVoiceBtn = document.getElementById('stop-voice');
        
        // 状态显示
        this.modelStatus = document.getElementById('model-status');
        this.responseTimeDisplay = document.getElementById('response-time');
        this.dailyQueriesDisplay = document.getElementById('daily-queries');
    }

    attachEventListeners() {
        // 发送消息
        this.sendBtn.addEventListener('click', () => this.handleSendMessage());
        this.questionInput.addEventListener('keydown', (e) => {
            if (e.key === 'Enter' && !e.shiftKey) {
                e.preventDefault();
                this.handleSendMessage();
            }
        });
        
        // 输入监听
        this.questionInput.addEventListener('input', () => {
            this.sendBtn.disabled = !this.questionInput.value.trim();
        });
        
        // 主题切换
        this.themeToggle.addEventListener('click', () => this.toggleTheme());
        
        // 清空对话
        this.clearChatBtn.addEventListener('click', () => this.clearChat());
        
        // 设置
        this.settingsBtn.addEventListener('click', () => this.openSettings());
        
        // 侧边栏
        this.sidebarToggle.addEventListener('click', () => this.toggleSidebar());
        
        // 语音输入
        this.voiceInputBtn.addEventListener('click', () => this.startVoiceInput());
        this.stopVoiceBtn.addEventListener('click', () => this.stopVoiceInput());
        
        // 图片上传
        this.imageUploadBtn.addEventListener('click', () => this.handleImageUpload());
        
        // 导出对话
        this.exportChatBtn.addEventListener('click', () => this.exportChat());
        
        // 模态框
        this.modalClose.addEventListener('click', () => this.closeModal());
        this.modalOverlay.addEventListener('click', (e) => {
            if (e.target === this.modalOverlay) this.closeModal();
        });
        
        // 反馈
        this.setupStarRating();
        this.submitFeedbackBtn.addEventListener('click', () => this.submitFeedback());
        this.skipFeedbackBtn.addEventListener('click', () => this.closeFeedback());
        this.closeFeedbackBtn.addEventListener('click', () => this.closeFeedback());
        
        // 快速问题
        document.querySelectorAll('.quick-question').forEach(btn => {
            btn.addEventListener('click', (e) => {
                const question = e.target.dataset.question;
                this.askQuestion(question);
            });
        });
        
        // 导航按钮
        document.querySelectorAll('.nav-btn').forEach(btn => {
            btn.addEventListener('click', (e) => {
                const action = e.target.dataset.action;
                this.handleNavigation(action);
            });
        });
        
        // 键盘快捷键
        document.addEventListener('keydown', (e) => {
            if (e.ctrlKey || e.metaKey) {
                switch (e.key) {
                    case 'Enter':
                        e.preventDefault();
                        this.handleSendMessage();
                        break;
                    case 'k':
                        e.preventDefault();
                        this.questionInput.focus();
                        break;
                    case 'l':
                        e.preventDefault();
                        this.clearChat();
                        break;
                }
            }
            if (e.key === 'Escape') {
                this.closeModal();
                this.closeFeedback();
            }
        });
    }

    initVoiceRecognition() {
        if ('webkitSpeechRecognition' in window || 'SpeechRecognition' in window) {
            const SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition;
            this.recognition = new SpeechRecognition();
            this.recognition.lang = 'zh-CN';
            this.recognition.continuous = false;
            this.recognition.interimResults = false;
            
            this.recognition.onresult = (event) => {
                const transcript = event.results[0][0].transcript;
                this.questionInput.value = transcript;
                this.sendBtn.disabled = false;
                this.stopVoiceInput();
            };
            
            this.recognition.onerror = (event) => {
                console.error('语音识别错误:', event.error);
                this.showNotification('语音识别失败，请重试', 'error');
                this.stopVoiceInput();
            };
            
            this.recognition.onend = () => {
                this.stopVoiceInput();
            };
        } else {
            this.voiceInputBtn.style.display = 'none';
        }
    }

    setupTheme() {
        const savedTheme = localStorage.getItem('theme') || 'light';
        this.setTheme(savedTheme);
    }

    setTheme(theme) {
        document.documentElement.setAttribute('data-theme', theme);
        localStorage.setItem('theme', theme);
        
        const icon = this.themeToggle.querySelector('i');
        icon.className = theme === 'dark' ? 'fas fa-sun' : 'fas fa-moon';
    }

    toggleTheme() {
        const currentTheme = document.documentElement.getAttribute('data-theme') || 'light';
        const newTheme = currentTheme === 'dark' ? 'light' : 'dark';
        this.setTheme(newTheme);
    }

    generateSessionId() {
        return 'session_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9);
    }

    async loadSystemStatus() {
        try {
            const response = await fetch('/api/monitor/dashboard');
            const data = await response.json();
            
            if (data.success) {
                this.dailyQueries = data.data.daily_queries || 0;
                this.responseTime = data.data.average_response_time || 0;
                
                this.dailyQueriesDisplay.textContent = this.dailyQueries;
                this.responseTimeDisplay.textContent = this.responseTime + 'ms';
            }
        } catch (error) {
            console.error('加载系统状态失败:', error);
        }
    }

    handleSendMessage() {
        const question = this.questionInput.value.trim();
        if (!question) return;
        
        this.askQuestion(question);
    }

    async askQuestion(question) {
        if (!question.trim()) return;

        // 隐藏欢迎页面，显示聊天界面
        this.showChatInterface();
        
        // 添加用户消息
        this.addMessage(question, 'user');
        
        // 清空输入框
        this.questionInput.value = '';
        this.sendBtn.disabled = true;
        
        // 显示加载状态
        this.addLoadingMessage();
        
        const startTime = Date.now();
        
        try {
            const response = await fetch('/api/qa/ask', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    question: question,
                    session_id: this.sessionId
                })
            });
            
            const data = await response.json();
            const endTime = Date.now();
            this.responseTime = endTime - startTime;
            
            // 移除加载消息
            this.removeLoadingMessage();
            
            if (data.error) {
                this.addMessage(`抱歉，处理您的问题时出现错误：${data.error}`, 'bot', 'error');
            } else {
                this.lastQuestion = question;
                this.lastAnswer = data.answer;
                
                // 格式化回答
                const formattedAnswer = this.formatAnswer(data.answer, data);
                this.addMessage(formattedAnswer, 'bot', 'success', data);
                
                // 更新系统状态
                this.dailyQueries++;
                this.dailyQueriesDisplay.textContent = this.dailyQueries;
                this.responseTimeDisplay.textContent = this.responseTime + 'ms';
                
                // 自动显示反馈面板（延迟）
                setTimeout(() => {
                    this.showFeedbackPanel();
                }, 2000);
            }
        } catch (error) {
            this.removeLoadingMessage();
            this.addMessage(`网络连接失败，请稍后重试。错误：${error.message}`, 'bot', 'error');
        }
    }

    formatAnswer(answer, data) {
        let formatted = answer;
        
        // 添加置信度信息
        if (data.confidence) {
            const confidenceLevel = data.confidence >= 0.8 ? '高' : 
                                  data.confidence >= 0.6 ? '中' : '低';
            formatted += `\n\n**置信度：${confidenceLevel}** (${Math.round(data.confidence * 100)}%)`;
        }
        
        // 添加相关科室
        if (data.department) {
            formatted += `\n\n**建议科室：** ${data.department}`;
        }
        
        // 添加注意事项
        if (data.warning) {
            formatted += `\n\n⚠️ **注意事项：** ${data.warning}`;
        }
        
        return formatted;
    }

    showChatInterface() {
        this.welcomeScreen.style.display = 'none';
        this.chatContainer.style.display = 'flex';
    }

    addMessage(text, sender, type = 'normal', data = null) {
        const messageDiv = document.createElement('div');
        messageDiv.className = `message ${sender}-message`;
        
        const time = new Date().toLocaleTimeString('zh-CN', { 
            hour: '2-digit', 
            minute: '2-digit' 
        });
        
        const avatar = sender === 'user' ? 
            '<i class="fas fa-user"></i>' : 
            '<i class="fas fa-robot"></i>';
        
        messageDiv.innerHTML = `
            <div class="message-avatar">${avatar}</div>
            <div class="message-content">
                <div class="message-header">
                    <span class="message-author">${sender === 'user' ? '您' : 'AI健康助手'}</span>
                    <span class="message-time">${time}</span>
                </div>
                <div class="message-text ${type}">${this.formatMessageText(text)}</div>
            </div>
        `;
        
        this.chatMessages.appendChild(messageDiv);
        this.chatMessages.scrollTop = this.chatMessages.scrollHeight;
        
        return messageDiv;
    }

    formatMessageText(text) {
        // 支持Markdown格式
        return text
            .replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>')
            .replace(/\*(.*?)\*/g, '<em>$1</em>')
            .replace(/\n/g, '<br>');
    }

    addLoadingMessage() {
        const loadingDiv = document.createElement('div');
        loadingDiv.className = 'message bot-message loading-message';
        loadingDiv.innerHTML = `
            <div class="message-avatar">
                <i class="fas fa-robot"></i>
            </div>
            <div class="message-content">
                <div class="message-header">
                    <span class="message-author">AI健康助手</span>
                    <span class="message-time">正在思考</span>
                </div>
                <div class="message-text">
                    <div class="loading-dots">
                        <span></span>
                        <span></span>
                        <span></span>
                    </div>
                </div>
            </div>
        `;
        
        this.chatMessages.appendChild(loadingDiv);
        this.chatMessages.scrollTop = this.chatMessages.scrollHeight;
    }

    removeLoadingMessage() {
        const loadingMessage = this.chatMessages.querySelector('.loading-message');
        if (loadingMessage) {
            loadingMessage.remove();
        }
    }

    clearChat() {
        if (confirm('确定要清空当前对话吗？此操作不可恢复。')) {
            this.chatMessages.innerHTML = `
                <div class="message bot-message">
                    <div class="message-avatar">
                        <i class="fas fa-robot"></i>
                    </div>
                    <div class="message-content">
                        <div class="message-header">
                            <span class="message-author">AI健康助手</span>
                            <span class="message-time">刚刚</span>
                        </div>
                        <div class="message-text">
                            您好！我是AI健康助手，请问有什么可以帮您的？
                        </div>
                    </div>
                </div>
            `;
            this.lastQuestion = null;
            this.lastAnswer = null;
            this.showNotification('对话已清空', 'success');
        }
    }

    startVoiceInput() {
        if (!this.recognition) {
            this.showNotification('您的浏览器不支持语音识别', 'error');
            return;
        }
        
        this.isRecording = true;
        this.voicePanel.style.display = 'block';
        this.recognition.start();
    }

    stopVoiceInput() {
        if (this.recognition) {
            this.recognition.stop();
        }
        this.isRecording = false;
        this.voicePanel.style.display = 'none';
    }

    handleImageUpload() {
        const input = document.createElement('input');
        input.type = 'file';
        input.accept = 'image/*';
        input.onchange = (e) => {
            const file = e.target.files[0];
            if (file) {
                this.uploadImage(file);
            }
        };
        input.click();
    }

    async uploadImage(file) {
        const formData = new FormData();
        formData.append('image', file);
        
        try {
            const response = await fetch('/api/qa/upload-image', {
                method: 'POST',
                body: formData
            });
            
            const data = await response.json();
            
            if (data.error) {
                this.showNotification('图片上传失败：' + data.error, 'error');
            } else {
                this.showNotification('图片上传成功', 'success');
                // 可以在这里处理图片识别结果
            }
        } catch (error) {
            this.showNotification('图片上传失败：' + error.message, 'error');
        }
    }

    exportChat() {
        const messages = Array.from(this.chatMessages.querySelectorAll('.message'));
        let chatContent = `AI健康助手对话记录\n`;
        chatContent += `会话ID: ${this.sessionId}\n`;
        chatContent += `导出时间: ${new Date().toLocaleString('zh-CN')}\n`;
        chatContent += '='.repeat(50) + '\n\n';
        
        messages.forEach(message => {
            const author = message.querySelector('.message-author').textContent;
            const time = message.querySelector('.message-time').textContent;
            const text = message.querySelector('.message-text').textContent;
            
            chatContent += `[${time}] ${author}:\n${text}\n\n`;
        });
        
        const blob = new Blob([chatContent], { type: 'text/plain;charset=utf-8' });
        const url = URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = `health-assistant-chat-${new Date().toISOString().split('T')[0]}.txt`;
        a.click();
        URL.revokeObjectURL(url);
        
        this.showNotification('对话已导出', 'success');
    }

    setupStarRating() {
        const stars = this.starRating.querySelectorAll('i');
        
        stars.forEach((star, index) => {
            star.addEventListener('click', () => {
                this.currentRating = index + 1;
                this.updateStarDisplay();
            });
            
            star.addEventListener('mouseenter', () => {
                this.highlightStars(index + 1);
            });
        });
        
        this.starRating.addEventListener('mouseleave', () => {
            this.highlightStars(this.currentRating);
        });
    }

    updateStarDisplay() {
        const stars = this.starRating.querySelectorAll('i');
        this.highlightStars(this.currentRating);
    }

    highlightStars(count) {
        const stars = this.starRating.querySelectorAll('i');
        stars.forEach((star, index) => {
            star.className = index < count ? 'fas fa-star' : 'far fa-star';
        });
    }

    showFeedbackPanel() {
        if (this.lastAnswer) {
            this.currentRating = 0;
            this.updateStarDisplay();
            this.feedbackText.value = '';
            this.feedbackPanel.style.display = 'block';
        }
    }

    closeFeedback() {
        this.feedbackPanel.style.display = 'none';
        this.currentRating = 0;
    }

    async submitFeedback() {
        if (this.currentRating === 0) {
            this.showNotification('请先选择评分', 'error');
            return;
        }
        
        const feedback = {
            question: this.lastQuestion,
            answer: this.lastAnswer,
            rating: this.currentRating,
            comment: this.feedbackText.value.trim(),
            session_id: this.sessionId
        };
        
        try {
            const response = await fetch('/api/qa/feedback', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(feedback)
            });
            
            const data = await response.json();
            
            if (data.success) {
                this.showNotification('感谢您的反馈！', 'success');
                this.closeFeedback();
            } else {
                this.showNotification('反馈提交失败：' + data.error, 'error');
            }
        } catch (error) {
            this.showNotification('反馈提交失败：' + error.message, 'error');
        }
    }

    openSettings() {
        this.modalTitle.textContent = '设置';
        this.modalBody.innerHTML = `
            <div class="settings-section">
                <h4>界面设置</h4>
                <div class="setting-item">
                    <label>
                        <input type="checkbox" id="auto-save-chat" ${localStorage.getItem('autoSave') !== 'false' ? 'checked' : ''}>
                        自动保存对话
                    </label>
                </div>
                <div class="setting-item">
                    <label>
                        <input type="checkbox" id="sound-notifications" ${localStorage.getItem('soundEnabled') !== 'false' ? 'checked' : ''}>
                        声音提醒
                    </label>
                </div>
                <div class="setting-item">
                    <label>响应时间目标：</label>
                    <select id="response-time-target">
                        <option value="1000">1秒</option>
                        <option value="2000">2秒</option>
                        <option value="3000">3秒</option>
                        <option value="5000">5秒</option>
                    </select>
                </div>
            </div>
            <div class="settings-section">
                <h4>隐私设置</h4>
                <div class="setting-item">
                    <button id="clear-history" class="btn-danger">清除所有历史记录</button>
                </div>
            </div>
        `;
        
        this.modalOverlay.style.display = 'flex';
        
        // 添加设置事件监听
        document.getElementById('auto-save-chat').addEventListener('change', (e) => {
            localStorage.setItem('autoSave', e.target.checked);
        });
        
        document.getElementById('sound-notifications').addEventListener('change', (e) => {
            localStorage.setItem('soundEnabled', e.target.checked);
        });
        
        document.getElementById('clear-history').addEventListener('click', () => {
            if (confirm('确定要清除所有历史记录吗？此操作不可恢复。')) {
                localStorage.clear();
                this.showNotification('历史记录已清除', 'success');
                this.closeModal();
            }
        });
    }

    closeModal() {
        this.modalOverlay.style.display = 'none';
    }

    toggleSidebar() {
        this.sidebar.classList.toggle('open');
    }

    handleNavigation(action) {
        const quickQuestions = {
            symptoms: '我最近总是头痛，可能是什么原因？',
            diseases: '请介绍一下高血压的症状和治疗方法',
            drugs: '感冒发烧应该吃什么药？',
            prevention: '如何预防高血压？'
        };
        
        if (quickQuestions[action]) {
            this.askQuestion(quickQuestions[action]);
        }
    }

    showNotification(message, type = 'info') {
        const notification = document.createElement('div');
        notification.className = `notification ${type}`;
        notification.innerHTML = `
            <div class="notification-content">
                <i class="fas fa-${this.getNotificationIcon(type)}"></i>
                <span>${message}</span>
            </div>
        `;
        
        document.getElementById('notification-container').appendChild(notification);
        
        setTimeout(() => {
            notification.style.opacity = '0';
            setTimeout(() => notification.remove(), 300);
        }, 3000);
    }

    getNotificationIcon(type) {
        const icons = {
            success: 'check-circle',
            error: 'exclamation-circle',
            warning: 'exclamation-triangle',
            info: 'info-circle'
        };
        return icons[type] || 'info-circle';
    }

    // 工具方法
    escapeHtml(text) {
        const div = document.createElement('div');
        div.textContent = text;
        return div.innerHTML;
    }

    debounce(func, wait) {
        let timeout;
        return function executedFunction(...args) {
            const later = () => {
                clearTimeout(timeout);
                func(...args);
            };
            clearTimeout(timeout);
            timeout = setTimeout(later, wait);
        };
    }
}

// 添加CSS样式
const additionalStyles = `
    .loading-dots {
        display: flex;
        gap: 4px;
    }
    
    .loading-dots span {
        width: 8px;
        height: 8px;
        border-radius: 50%;
        background: var(--gray-500);
        animation: loadingDot 1.4s infinite ease-in-out both;
    }
    
    .loading-dots span:nth-child(1) { animation-delay: -0.32s; }
    .loading-dots span:nth-child(2) { animation-delay: -0.16s; }
    
    @keyframes loadingDot {
        0%, 80%, 100% {
            transform: scale(0.8);
            opacity: 0.5;
        }
        40% {
            transform: scale(1);
            opacity: 1;
        }
    }
    
    .notification-content {
        display: flex;
        align-items: center;
        gap: var(--spacing-sm);
    }
    
    .settings-section {
        margin-bottom: var(--spacing-lg);
    }
    
    .settings-section h4 {
        margin-bottom: var(--spacing-md);
        color: var(--gray-700);
    }
    
    .setting-item {
        margin-bottom: var(--spacing-sm);
    }
    
    .setting-item label {
        display: flex;
        align-items: center;
        gap: var(--spacing-sm);
        cursor: pointer;
    }
    
    .btn-danger {
        background: var(--danger-color);
        color: var(--white);
        border: none;
        padding: var(--spacing-sm) var(--spacing-md);
        border-radius: var(--radius-md);
        cursor: pointer;
    }
    
    .btn-danger:hover {
        background: var(--error-color);
    }
`;

// 添加样式到页面
const styleSheet = document.createElement('style');
styleSheet.textContent = additionalStyles;
document.head.appendChild(styleSheet);

// 初始化应用
document.addEventListener('DOMContentLoaded', () => {
    window.medicalApp = new MedicalQAApp();
    console.log('🚀 AI健康助手已启动');
});

// 导出供其他模块使用
if (typeof module !== 'undefined' && module.exports) {
    module.exports = MedicalQAApp;
}